<template>
	<view class="container">
		<!-- Loading -->
		<view class="loading" v-if="loading">
			<image src="/static/images/loading.gif"></image>
			<text>加载中...</text>
		</view>
		
		<!-- Content -->
		<block v-else>
			<view class="header">
			
				<view class="title">预约详情</view>
				<view :class="['status-tag', getStatusClass(appointmentData.status)]">{{ formatStatus(appointmentData.status) }}</view>
			</view>
			
			<!-- Visitor Info -->
			<view class="info-section">
				<view class="section-title">访客信息</view>
				<view class="info-item">
					<text class="label">姓名</text>
					<text class="value">{{ appointmentData.visitor?.name || appointmentData.visitor_info?.name || '未提供' }}</text>
				</view>
				<view class="info-item">
					<text class="label">手机号</text>
					<text class="value">{{ appointmentData.visitor?.phone || appointmentData.visitor_info?.phone || '未提供' }}</text>
				</view>
				<view class="info-item" v-if="appointmentData.visitor?.gender || appointmentData.visitor_info?.gender">
					<text class="label">性别</text>
					<text class="value">{{ (appointmentData.visitor?.gender || appointmentData.visitor_info?.gender) === 'M' ? '男' : '女' }}</text>
				</view>
				<view class="info-item" v-if="(appointmentData.visitor?.id_card || appointmentData.visitor_info?.id_card) && (appointmentData.visitor?.id_card || appointmentData.visitor_info?.id_card).trim()">
					<text class="label">身份证号</text>
					<text class="value">{{ formatIdCard(appointmentData.visitor?.id_card || appointmentData.visitor_info?.id_card) }}</text>
				</view>
				<view class="info-item" v-if="(appointmentData.visitor?.email || appointmentData.visitor_info?.email) && (appointmentData.visitor?.email || appointmentData.visitor_info?.email).trim()">
					<text class="label">邮箱</text>
					<text class="value">{{ appointmentData.visitor?.email || appointmentData.visitor_info?.email }}</text>
				</view>
				<view class="info-item" v-if="(appointmentData.visitor?.company || appointmentData.visitor_info?.company) && (appointmentData.visitor?.company || appointmentData.visitor_info?.company).trim()">
					<text class="label">公司</text>
					<text class="value">{{ appointmentData.visitor?.company || appointmentData.visitor_info?.company }}</text>
				</view>
			</view>
			
			<!-- Appointment Info -->
			<view class="info-section">
				<view class="section-title">预约信息</view>
				<view class="info-item">
					<text class="label">预约时间</text>
					<text class="value">{{ appointmentData.expected_visit_time }}</text>
				</view>
				<view class="info-item">
					<text class="label">来访目的</text>
					<text class="value">{{ appointmentData.visit_purpose }}</text>
				</view>
				<view class="info-item" v-if="appointmentData.visited_company">
					<text class="label">被访企业</text>
					<text class="value">{{ appointmentData.visited_company.company_name }}</text>
				</view>
				<view class="info-item" v-else-if="appointmentData.visited_company_name">
					<text class="label">被访企业</text>
					<text class="value">{{ appointmentData.visited_company_name }}</text>
				</view>
				
				<view class="info-item" v-if="appointmentData.created_at">
					<text class="label">创建时间</text>
					<text class="value">{{ appointmentData.created_at }}</text>
				</view>
			</view>
			
			<!-- QR Code Section -->
			<view class="qrcode-section">
				<view class="qrcode-title">入园凭证</view>
				<view class="qrcode-container">
					<image class="qrcode-image" src="/static/二维码.png" mode="aspectFit"></image>
					<view class="qrcode-info">
						<view class="qrcode-name">{{ appointmentData.visitor?.name || appointmentData.visitor_info?.name || '访客' }}</view>
						<view class="qrcode-time">{{ appointmentData.expected_visit_time }}</view>
					</view>
				</view>
				<view class="qrcode-tip">请向门卫出示此二维码</view>
				<view class="qrcode-actions">
					<view class="qrcode-btn save-btn" @click="saveQrCode">
						<text class="iconfont icon-download"></text>
						<text>保存二维码</text>
					</view>
				</view>
			</view>
			
			<!-- Action Buttons -->
			<view class="action-btns" v-if="canCancel || canModify">
				<view class="btn cancel-btn" v-if="canCancel" @click="cancelAppointment">取消预约</view>
				<view class="btn modify-btn" v-if="canModify" @click="editAppointment">修改预约</view>
			</view>
		</block>
	</view>
</template>

<script>
import { visitorAppointmentAPI } from '@/api/services.js';

export default {
	data() {
		return {
			appointmentId: null,
			appointmentData: {
				visitor: {},
				visitor_info: {}
			},
			loading: false
		};
	},
	computed: {
		// 是否可以取消预约
		canCancel() {
			return ['pending', 'approved', 0, 1].includes(this.appointmentData.status);
		},
		// 是否可以修改预约
		canModify() {
			return ['pending', 0].includes(this.appointmentData.status);
		}
	},
	onLoad(options) {
		if (options.id) {
			this.appointmentId = options.id;
			this.getAppointmentDetail();
		} else {
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	methods: {
		// 获取预约详情
		getAppointmentDetail() {
			this.loading = true;
			
			// 检查是否是本地预约
			if (this.appointmentId.startsWith('local_')) {
				// 从本地缓存获取预约数据
				const localAppointments = uni.getStorageSync('localAppointments') || [];
				const appointment = localAppointments.find(item => item.appointment_id === this.appointmentId);
				
				if (appointment) {
					// 构造详情数据
					this.appointmentData = {
						appointment_id: appointment.appointment_id,
						visitor_info: {
							name: appointment.visitor_name,
							phone: appointment.visitor_phone,
							gender: appointment.visitor_gender,
							id_card: appointment.visitor_id_card,
							email: appointment.visitor_email,
							company: appointment.visitor_company
						},
						visit_purpose: appointment.visit_purpose,
						expected_visit_time: appointment.expected_visit_time,
						visited_company_id: appointment.visited_company_id,
						visited_company_name: this.getCompanyNameById(appointment.visited_company_id),
						accompanier_info: appointment.accompanier_info,
						status: appointment.status,
						created_at: appointment.created_at
					};
					
					this.loading = false;
					return;
				}
			}
			
			// 如果不是本地预约或未找到，尝试从API获取
			visitorAppointmentAPI.getAppointmentDetail(this.appointmentId)
				.then(res => {
					console.log('获取预约详情响应:', res);
					if (res.code === 200 && res.data) {
						// 处理API返回的数据
						this.appointmentData = res.data;
						
						// 如果返回的数据中没有visited_company_name但有visited_company
						if (!this.appointmentData.visited_company_name && this.appointmentData.visited_company) {
							this.appointmentData.visited_company_name = this.appointmentData.visited_company.company_name;
						}
						
						// 格式化日期时间
						if (this.appointmentData.expected_visit_time) {
							this.appointmentData.expected_visit_time = this.formatDateTime(this.appointmentData.expected_visit_time);
						}
						
						if (this.appointmentData.created_at) {
							this.appointmentData.created_at = this.formatDateTime(this.appointmentData.created_at);
						}
						
						console.log('处理后的预约详情:', this.appointmentData);
					} else {
						uni.showToast({
							title: res.message || '获取预约详情失败',
							icon: 'none'
						});
					}
				})
				.catch(err => {
					uni.showToast({
						title: '获取预约详情失败',
						icon: 'none'
					});
					console.error('获取预约详情失败:', err);
				})
				.finally(() => {
					this.loading = false;
				});
		},
		
		// 根据公司ID获取公司名称
		getCompanyNameById(companyId) {
			const companyMap = {
				1: '某某科技有限公司',
				2: '某某贸易有限公司',
				3: '某某服务有限公司'
			};
			return companyMap[companyId] || '未知公司';
		},
		
		// 取消预约
		cancelAppointment() {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消此预约吗？',
				success: (res) => {
					if (res.confirm) {
						this.loading = true;
						
						// 检查是否是本地预约
						if (this.appointmentId.startsWith('local_')) {
							// 从本地缓存获取预约数据
							const localAppointments = uni.getStorageSync('localAppointments') || [];
							const index = localAppointments.findIndex(item => item.appointment_id === this.appointmentId);
							
							if (index !== -1) {
								// 更新状态
								localAppointments[index].status = 'cancelled';
								uni.setStorageSync('localAppointments', localAppointments);
								
								// 更新当前数据
								this.appointmentData.status = 'cancelled';
								
								uni.showToast({
									title: '预约已取消',
									icon: 'success'
								});
								
								this.loading = false;
								return;
							}
						}
						
						// 如果不是本地预约或未找到，尝试通过API取消
						visitorAppointmentAPI.updateAppointment(this.appointmentId, {
							status: 5  // 使用数字状态码 5 表示已取消
						})
							.then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '预约已取消',
										icon: 'success'
									});
									
									// 刷新详情
									setTimeout(() => {
										this.getAppointmentDetail();
									}, 1500);
								} else {
									uni.showToast({
										title: res.message || '取消预约失败',
										icon: 'none'
									});
								}
							})
							.catch(err => {
								uni.showToast({
									title: '取消预约失败',
									icon: 'none'
								});
								console.error('取消预约失败:', err);
							})
							.finally(() => {
								this.loading = false;
							});
					}
				}
			});
		},
		
		// 编辑预约
		editAppointment() {
			uni.navigateTo({
				url: `/pages/appointment/edit?id=${this.appointmentId}`
			});
		},
		
		// 格式化状态显示
		formatStatus(status) {
			const statusMap = {
				0: '待审批',
				1: '已批准',
				2: '已拒绝',
				3: '已入园',
				4: '已离园',
				5: '已取消',
				'pending': '待审批',
				'approved': '已批准',
				'rejected': '已拒绝',
				'visited': '已入园',
				'cancelled': '已取消'
			};
			return statusMap[status] || status;
		},
		
		// 获取状态样式
		getStatusClass(status) {
			// 数字状态码映射
			const statusMap = {
				0: 'status-pending',    // 待审批
				1: 'status-approved',   // 已批准
				2: 'status-rejected',   // 已拒绝
				3: 'status-entered',    // 已入园
				4: 'status-left',       // 已离园
				5: 'status-cancelled'   // 已取消
			};
			
			// 如果是数字状态码，直接映射
			if (typeof status === 'number' && statusMap[status]) {
				return statusMap[status];
			}
			
			// 如果是字符串状态，使用原有映射
			switch (status) {
				case 'pending':
					return 'status-pending';
				case 'approved':
					return 'status-approved';
				case 'rejected':
					return 'status-rejected';
				case 'visited':
					return 'status-entered';
				case 'cancelled':
					return 'status-cancelled';
				default:
					return '';
			}
		},
		
		// 返回列表页
		goBack() {
			uni.navigateBack();
		},
		
		// 保存二维码到相册
		saveQrCode() {
			if (!this.appointmentData.qr_code) {
				uni.showToast({
					title: '二维码不存在',
					icon: 'none'
				});
				return;
			}
			
			// 将base64转为临时文件
			const base64Data = this.appointmentData.qr_code.split(',')[1];
			const arrayBuffer = uni.base64ToArrayBuffer(base64Data);
			const filePath = `${wx.env.USER_DATA_PATH}/appointment_qrcode_${this.appointmentId}.png`;
			
			uni.getFileSystemManager().writeFile({
				filePath: filePath,
				data: arrayBuffer,
				encoding: 'binary',
				success: () => {
					// 保存到相册
					uni.saveImageToPhotosAlbum({
						filePath: filePath,
						success: () => {
							uni.showToast({
								title: '二维码已保存到相册',
								icon: 'success'
							});
						},
						fail: (err) => {
							uni.showToast({
								title: '保存失败，请授权相册权限',
								icon: 'none'
							});
							console.error('保存到相册失败:', err);
						}
					});
				},
				fail: (err) => {
					uni.showToast({
						title: '二维码保存失败',
						icon: 'none'
					});
					console.error('写入文件失败:', err);
				}
			});
		},
		
		// 格式化身份证号码（中间部分用星号替代）
		formatIdCard(idCard) {
			if (!idCard) return '';
			idCard = idCard.trim();
			if (!idCard) return '';
			
			if (idCard.length === 18) {
				return `${idCard.substring(0, 6)}********${idCard.substring(14)}`;
			}
			return idCard;
		},
		
		// 格式化日期时间
		formatDateTime(datetime) {
			if (!datetime) return '';
			
			try {
				const date = new Date(datetime);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			} catch (error) {
				console.error('日期格式化错误:', error);
				return datetime;
			}
		},
		
		// 格式化陪同人信息
		formatAccompanierInfo(info) {
			if (!info) return '';
			
			try {
				// 如果是JSON字符串，尝试解析
				if (typeof info === 'string') {
					if (info === '[]') return '无';
					
					const accompanierArray = JSON.parse(info);
					if (Array.isArray(accompanierArray)) {
						if (accompanierArray.length === 0) return '无';
						
						// 如果是数组对象，格式化为字符串
						return accompanierArray.map(person => {
							if (typeof person === 'object') {
								return `${person.name || ''}${person.phone ? ` (${person.phone})` : ''}`;
							}
							return person;
						}).join(', ');
					}
					
					return info;
				}
				
				// 如果已经是对象或数组，直接使用
				if (Array.isArray(info)) {
					return info.join(', ');
				}
				
				return String(info);
			} catch (error) {
				console.error('格式化陪同人信息出错:', error);
				return String(info);
			}
		}
	}
};
</script>

<style lang="scss">
.container {
	padding: 0;
	background-color: #F2F2F7;
	min-height: 100vh;
}

.loading {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading image {
	width: 160rpx;
	height: 160rpx;
	margin-bottom: 20rpx;
	opacity: 0.7;
}

.loading text {
	color: #8E8E93;
	font-size: 28rpx;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 20rpx;
	background-color: #FFFFFF;
	position: relative;
}

.back-btn {
	position: absolute;
	left: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title {
	font-size: 34rpx;
	font-weight: 600;
	text-align: center;
	flex: 1;
	color: #1C1C1E;
}

.status-tag {
	padding: 6rpx 16rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	font-weight: 500;
}

.status-pending {
	background-color: transparent;
	color: #F5A623;
	border: 1rpx solid #F5A623;
}

.status-approved {
	background-color: transparent;
	color: #4A89DC;
	border: 1rpx solid #4A89DC;
}

.status-rejected {
	background-color: transparent;
	color: #D85140;
	border: 1rpx solid #D85140;
}

.status-entered {
	background-color: transparent;
	color: #4CD964;
	border: 1rpx solid #4CD964;
}

.status-cancelled {
	background-color: transparent;
	color: #8E8E93;
	border: 1rpx solid #8E8E93;
}

.info-section {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 24rpx;
	margin: 16rpx;
	box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.03);
}

.section-title {
	font-size: 30rpx;
	font-weight: 600;
	margin-bottom: 20rpx;
	color: #1C1C1E;
	position: relative;
	padding-left: 16rpx;
}

.section-title::before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 6rpx;
	height: 24rpx;
	background-color: #4A89DC;
	border-radius: 3rpx;
}

.info-item {
	display: flex;
	margin-bottom: 16rpx;
}

.info-item:last-child {
	margin-bottom: 0;
}

.label {
	width: 160rpx;
	color: #8E8E93;
	font-size: 28rpx;
}

.value {
	flex: 1;
	color: #1C1C1E;
	font-size: 28rpx;
}

.qrcode-section {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 24rpx;
	margin: 16rpx;
	box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.03);
	display: flex;
	flex-direction: column;
	align-items: center;
}

.qrcode-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #1C1C1E;
	margin-bottom: 24rpx;
	align-self: flex-start;
	position: relative;
	padding-left: 16rpx;
}

.qrcode-title::before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 6rpx;
	height: 24rpx;
	background-color: #4A89DC;
	border-radius: 3rpx;
}

.qrcode-container {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30rpx 0;
	border-radius: 12rpx;
	background: linear-gradient(to bottom, #F9F9F9, #FFFFFF);
	border: 1rpx dashed #E5E5EA;
}

.qrcode-image {
	width: 320rpx;
	height: 320rpx;
	margin-bottom: 20rpx;
}

.qrcode-info {
	text-align: center;
	margin-bottom: 10rpx;
}

.qrcode-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #1C1C1E;
	margin-bottom: 8rpx;
}

.qrcode-time {
	font-size: 26rpx;
	color: #8E8E93;
}

.qrcode-tip {
	font-size: 26rpx;
	color: #8E8E93;
	margin: 20rpx 0;
}

.qrcode-actions {
	display: flex;
	width: 100%;
	justify-content: space-around;
	margin-top: 10rpx;
}

.qrcode-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 12rpx 30rpx;
	border-radius: 8rpx;
	font-size: 26rpx;
}

.qrcode-btn text {
	margin: 0 4rpx;
}

.save-btn {
	background-color: transparent;
	color: #4A89DC;
	border: 1rpx solid #4A89DC;
}

.refresh-btn {
	background-color: transparent;
	color: #8E8E93;
	border: 1rpx solid #8E8E93;
}

.action-btns {
	display: flex;
	justify-content: space-between;
	padding: 16rpx;
	margin-top: 20rpx;
}

.btn {
	width: 48%;
	height: 88rpx;
	border-radius: 12rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 30rpx;
	font-weight: 500;
}

.cancel-btn {
	background-color: transparent;
	color: #8E8E93;
	border: 1rpx solid #8E8E93;
}

.modify-btn {
	background-color: transparent;
	color: #4A89DC;
	border: 1rpx solid #4A89DC;
}

.btn:active {
	opacity: 0.8;
}

/* 图标字体 */
@font-face {
	font-family: "iconfont";
	src: url('data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAOMAAsAAAAAB5gAAAM+AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDHAqCYIJGATYCJAMQCwoABCAFhGcHShuTBsgOJUHBwAAAAAFEBNmwzd7dJyZpkjaJRtM0iUQoFAqJRIJEpyP0/D+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9R6lhCJGPAmlx5oOLckNLZXl5ky7AgA=');
}

.iconfont {
	font-family: "iconfont" !important;
	font-size: 28rpx;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-left:before {
	content: "\e6a5";
}

.icon-download:before {
	content: "\e6a6";
}

.icon-refresh:before {
	content: "\e6a7";
}
</style> 